﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Xml;
using System.Net;
using System.IO;

namespace BingDownloader
{
    static class VersionHelper
    {
        static Version currentVersion;
        public static Version latestVersion;
        public static Uri downloadUri;
        static string assemblyName;

        static VersionHelper()
        {
            assemblyName = Assembly.GetExecutingAssembly().GetName().Name;
            currentVersion = new Version(Assembly.GetExecutingAssembly().GetName().Version.ToString());
        }

        public static bool CheckForLatestWithURL(string strURL)
        {
                    
            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strURL);
            request.Proxy = WebRequest.GetSystemWebProxy();
            request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;
            // execute the request
            HttpWebResponse response = null;
            try
            {
                response = (HttpWebResponse) request.GetResponse();
            }
            catch (Exception /*e*/)
            {     
                //ignore if version check cannot be made now
                //throw new ApplicationException("Internet Access is not available!");
                return false;
            }
           
            string webContent = string.Empty;
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                webContent = sr.ReadToEnd();
            }                      
        
            // parse the xml content
            webContent = webContent.Replace("&amp;", "&");
            webContent = webContent.Replace("&", "&amp;");
            webContent = webContent.Replace("\\s+", " ");
            XmlDocument xdoc = new XmlDocument();
            xdoc.LoadXml(webContent);

            XmlNodeList nodeList = xdoc.SelectNodes("//PRODUCT");

            foreach (XmlNode node in nodeList)
            {
                if (node.Attributes["NAME"].Value.ToString() == assemblyName)
                {
                    latestVersion = new Version(node.Attributes["VERSION"].Value.ToString());
                    downloadUri = new Uri(node.Attributes["DOWNLOADURL"].Value.ToString());
                }
            }

            if (latestVersion > currentVersion)
                return true;
            else 
                return false;
        }
    }
}
